﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MutilPanel
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //定义一个字典，用来记录每个子面板在主界面Grid.Column中的位置
        Dictionary<int, int> dic_panel = new Dictionary<int, int>();

        private List<ChildPanel> childPanels = new List<ChildPanel>();
        public MainWindow()
        {
            InitializeComponent();
            InitializeSubPanels();
            //// 初始化时生成两个子面板
            //for (int i = 0; i < 2; i++)
            //{
            //    var userControl = new ChildPanel();
            //    childPanels.Add(userControl);
            //    AddUserControlToMainWindow(userControl);
            //}
        }

        private void InitializeSubPanels()
        {
            // 创建第一个子面板
            var userControl1 = new ChildPanel(2);
            mainGrid.Children.Add(userControl1);
            Grid.SetColumn(userControl1, 0);
            dic_panel.Add(userControl1._controlType, 0);

            // 创建第二个子面板
            var userControl2 = new ChildPanel(3);
            mainGrid.Children.Add(userControl2);
            Grid.SetColumn(userControl2, 1);
            dic_panel.Add(userControl2._controlType, 1);
        }

        public void AddUserControlToMainWindow(ChildPanel userControl)
        {
            // 检查是否已经存在于其他容器中
            if (userControl.Parent != null)
            {
                // 找到父容器，断开父级容器,父级容器的逻辑属性设置为空
                userControl.Parent.SetValue(ContentPresenter.ContentProperty, null);
            }
            mainGrid.Children.Add(userControl);
            Grid.SetColumn(userControl, dic_panel[userControl._controlType]);
            userControl.Width = Double.NaN; // 设置宽度为 Double.NaN，以适应主窗口的变化
            mainGrid.ColumnDefinitions[dic_panel[userControl._controlType]].Width = new GridLength(1, GridUnitType.Star);
        }
        public void RemoveUserControlFromMainWindow(ChildPanel userControl)
        {
            // 确保用户控件在移除前仍然存在
            if (mainGrid.Children.Contains(userControl))
            {
                mainGrid.Children.Remove(userControl);
                mainGrid.ColumnDefinitions[dic_panel[userControl._controlType]].Width = GridLength.Auto;
                mainGrid.ColumnDefinitions[1 - dic_panel[userControl._controlType]].Width = new GridLength(1, GridUnitType.Star);
            }
        }
    }
}
